// 导入docx库所需的类和方法
import { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, HeadingLevel, AlignmentType, SectionType } from 'docx';

// 文档元素类型枚举
export enum DocumentElementType {
  PARAGRAPH = 'paragraph',
  HEADING = 'heading',
  LIST_ITEM = 'listItem',
  TABLE = 'table',
  CODE_BLOCK = 'codeBlock',
  BLOCK_QUOTE = 'blockQuote'
}

/**
 * 文档元素接口
 */
export interface DocumentElement {
  type: DocumentElementType;
  content: string | any[];
  metadata?: { [key: string]: any };
}

/**
 * 中间文档格式接口
 */
export interface IntermediateDocument {
  title?: string;
  content: DocumentElement[];
  metadata?: { [key: string]: any };
}

/**
 * Markdown到中间文档格式的转换器
 */
export class MarkdownToIntermediateConverter {
  /**
   * 将Markdown文本转换为中间文档格式
   * @param markdownText Markdown文本内容
   * @returns 中间文档格式对象
   */
  public convert(markdownText: string): IntermediateDocument {
    const document: IntermediateDocument = {
      content: []
    };

    // 按行分割文本
    const lines = markdownText.split('\n');
    let i = 0;
    
    // 处理每一行
    while (i < lines.length) {
      const line = lines[i].trim();
      
      // 跳过空行
      if (line === '') {
        i++;
        continue;
      }
      
      // 处理标题
      if (line && line.startsWith('#')) {
        const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
        if (headingMatch && headingMatch.length >= 3) {
          const level = headingMatch[1].length;
          const text = headingMatch[2];
          
          document.content.push({
            type: DocumentElementType.HEADING,
            content: text || '',
            metadata: { level }
          });
          i++;
          continue;
        }
      }
      
      // 处理列表项
      if (line && (line.startsWith('- ') || line.startsWith('* ') || line.match(/^\d+\.\s+/))) {
        let listContent = line.substring(line.indexOf(' ') + 1) || '';
        i++;
        
        // 收集列表项的后续行（如果有）
        while (i < lines.length && lines[i] && lines[i].trim().startsWith('  ')) {
          listContent += '\n' + lines[i].trim();
          i++;
        }
        
        document.content.push({
          type: DocumentElementType.LIST_ITEM,
          content: listContent
        });
        continue;
      }
      
      // 处理代码块
      if (line && line.startsWith('```')) {
        const language = line.substring(3).trim() || 'text';
        let codeContent = '';
        i++;
        
        // 收集代码块内容，直到遇到结束标记
        while (i < lines.length && lines[i] && !lines[i].startsWith('```')) {
          codeContent += lines[i] + '\n';
          i++;
        }
        
        document.content.push({
          type: DocumentElementType.CODE_BLOCK,
          content: codeContent.trim(),
          metadata: { language }
        });
        i++;
        continue;
      }
      
      // 处理引用块
      if (line && line.startsWith('>')) {
        let quoteContent = line.substring(1).trim() || '';
        i++;
        
        // 收集引用块的后续行
        while (i < lines.length && lines[i] && lines[i].startsWith('>')) {
          quoteContent += '\n' + lines[i].substring(1).trim();
          i++;
        }
        
        document.content.push({
          type: DocumentElementType.BLOCK_QUOTE,
          content: quoteContent
        });
        continue;
      }
      
      // 处理表格（简单的CSV风格表格）
      if (line && line.includes('|') && i + 1 < lines.length && lines[i + 1] && lines[i + 1].includes('|') && lines[i + 1].includes('-')) {
        const tableContent = [];
        let hasHeader = true;
        
        // 收集表格的所有行
        while (i < lines.length && lines[i] && lines[i].includes('|')) {
          const row = lines[i].split('|').map(cell => cell.trim()).filter(cell => cell !== '');
          tableContent.push(row);
          i++;
        }
        
        // 移除表格分隔符行
        if (tableContent.length > 1 && tableContent[1] && tableContent[1].every(cell => cell.startsWith('-'))) {
          tableContent.splice(1, 1);
        }
        
        document.content.push({
          type: DocumentElementType.TABLE,
          content: tableContent,
          metadata: { hasHeader }
        });
        continue;
      }
      
      // 默认处理为段落
      let paragraphContent = line || '';
      i++;
      
      // 收集段落的后续行
      while (i < lines.length && lines[i] && lines[i].trim() !== '') {
        paragraphContent += ' ' + lines[i].trim();
        i++;
      }
      
      document.content.push({
        type: DocumentElementType.PARAGRAPH,
        content: paragraphContent
      });
    }
    
    return document;
  }
}

/**
 * 中间文档格式到Word的转换器
 */
export class IntermediateToWordConverter {
  /**
   * 将中间文档格式转换为Word文档
   * @param intermediateDocument 中间文档格式对象
   * @returns Promise<Blob> Word文档的Blob对象
   */
  public async convert(intermediateDocument: IntermediateDocument): Promise<Blob> {
    // 检查中间文档是否有效
    if (!intermediateDocument || !intermediateDocument.content || intermediateDocument.content.length === 0) {
      throw new Error('中间文档格式无效或内容为空');
    }

    console.log('开始创建Word文档对象...');
    
    // 创建一个新的Word文档，使用更简洁的配置方式
    const doc = new Document({
      creator: 'MDToWord Converter',
      title: intermediateDocument.title || 'Converted Document',
      description: 'Document converted from Markdown',
      sections: [{
        properties: {},  // 添加properties属性
        children: []     // 确保children是一个空数组
      }]
    });
    
    console.log('Word文档对象创建成功');
    
    // 直接获取sections[0].children，避免复杂的条件判断
    const children = doc.sections[0].children;
    
    // 添加调试信息
    console.log(`处理文档内容，元素数量: ${intermediateDocument.content.length}`);
    
    // 处理文档内容
    intermediateDocument.content.forEach((element, index) => {
      console.log(`处理第${index + 1}个元素，类型: ${element.type}`);
      switch (element.type) {
        case DocumentElementType.PARAGRAPH:
          // 创建段落并添加到文档
          try {
            const paragraph = new Paragraph({
              children: [
                new TextRun({
                  text: (element.content as string) || '',  // 确保文本不为null或undefined
                  size: 24,
                  font: '微软雅黑'
                })
              ],
              spacing: {
                after: 120
              }
            });
            children.push(paragraph);
            console.log('添加段落成功');
          } catch (error) {
            console.error('创建段落时出错:', error);
          }
          break;
          
        case DocumentElementType.HEADING:
          try {
            const headingLevel = (element.metadata?.level as number) || 1;
            const headingText = element.content as string;
            
            // 创建标题并添加到文档
            const headingParagraph = new Paragraph({
              children: [
                new TextRun({
                  text: headingText || '',  // 确保文本不为null或undefined
                  size: headingLevel === 1 ? 36 : headingLevel === 2 ? 32 : headingLevel === 3 ? 28 : 24,
                  bold: true,
                  font: '微软雅黑'
                })
              ],
              heading: Math.min(Math.max(headingLevel, 1), 6),  // 直接使用数字作为级别
              spacing: {
                after: 120
              }
            });
            children.push(headingParagraph);
            console.log(`添加${headingLevel}级标题成功`);
          } catch (error) {
            console.error('创建标题时出错:', error);
          }
          break;
          
        case DocumentElementType.LIST_ITEM:
          // 创建列表项并添加到文档
          try {
            const listParagraph = new Paragraph({
              children: [
                new TextRun({
                  text: '• ' + ((element.content as string) || ''),  // 确保文本不为null或undefined
                  size: 24,
                  font: '微软雅黑'
                })
              ],
              bullet: {
                level: 0
              },
              spacing: {
                after: 60
              }
            });
            children.push(listParagraph);
            console.log('添加列表项成功');
          } catch (error) {
            console.error('创建列表项时出错:', error);
          }
          break;
          
        case DocumentElementType.CODE_BLOCK:
          // 创建代码块并添加到文档
          try {
            const codeParagraph = new Paragraph({
              children: [
                new TextRun({
                  text: (element.content as string) || '',  // 确保文本不为null或undefined
                  size: 20,
                  font: 'Courier New',
                  color: '#000000'
                })
              ],
              shading: {
                fill: '#f5f5f5'
              },
              indent: {
                left: 360
              },
              spacing: {
                after: 120
              }
            });
            children.push(codeParagraph);
            console.log('添加代码块成功');
          } catch (error) {
            console.error('创建代码块时出错:', error);
          }
          break;
          
        case DocumentElementType.BLOCK_QUOTE:
          // 创建引用块并添加到文档
          try {
            const quoteParagraph = new Paragraph({
              children: [
                new TextRun({
                  text: (element.content as string) || '',  // 确保文本不为null或undefined
                  size: 24,
                  font: '微软雅黑',
                  color: '#555555'
                })
              ],
              indent: {
                left: 360,
                right: 360
              },
              shading: {
                fill: '#f9f9f9'
              },
              spacing: {
                after: 120
              }
            });
            children.push(quoteParagraph);
            console.log('添加引用块成功');
          } catch (error) {
            console.error('创建引用块时出错:', error);
          }
          break;
          
        case DocumentElementType.TABLE:
          try {
            const tableContent = element.content as string[][];
            if (!tableContent || tableContent.length === 0) {
              console.log('表格内容为空，跳过');
              break;
            }
            
            console.log(`处理表格，行数: ${tableContent.length}`);
            
            const table = new Table({
              rows: []
            });
            
            // 创建表格行和单元格
            const rows = [];
            
            // 创建表头行
            if (tableContent[0] && tableContent[0].length > 0) {
              const headerCells = tableContent[0].map(cellContent => {
                return new TableCell({
                  children: [new Paragraph({
                    children: [new TextRun({
                      text: cellContent || '',  // 确保文本不为null或undefined
                      bold: true,
                      size: 24,
                      font: '微软雅黑'
                    })],
                    alignment: AlignmentType.CENTER
                  })]
                });
              });
              
              rows.push(new TableRow({ children: headerCells }));
            }
            
            // 创建数据行
            for (let i = 1; i < tableContent.length; i++) {
              if (tableContent[i] && tableContent[i].length > 0) {
                const cells = tableContent[i].map(cellContent => {
                  return new TableCell({
                    children: [new Paragraph({
                      children: [new TextRun({
                        text: cellContent || '',  // 确保文本不为null或undefined
                        size: 24,
                        font: '微软雅黑'
                      })]
                    })]
                  });
                });
                
                rows.push(new TableRow({ children: cells }));
              }
            }
            
            // 创建表格并设置行
            const table = new Table({
              rows: rows
            });
            
            // 添加空段落和表格
            children.push(new Paragraph({ children: [] }));
            children.push(table);
            children.push(new Paragraph({ children: [] }));
            console.log('添加表格成功');
          } catch (error) {
            console.error('创建表格时出错:', error);
          }
          break;
      }
    });
    
    // 确保文档至少有一个段落
    if (children.length === 0) {
      children.push(new Paragraph({
        children: [
          new TextRun({
            text: '文档内容为空',
            size: 24,
            font: '微软雅黑'
          })
        ]
      }));
    }
    
    console.log(`文档处理完成，共添加了${children.length}个元素`);
    
    try {
      // 打包文档并返回Blob
      console.log('开始打包文档...');
      const blob = await Packer.toBlob(doc);
      console.log(`文档打包成功，Blob大小: ${blob.size} 字节`);
      
      // 检查生成的Blob是否有效
      if (!blob || blob.size === 0) {
        throw new Error('生成的Word文档Blob为空');
      }
      
      return blob;
    } catch (error) {
      console.error('打包文档时出错:', error);
      // 安全地处理错误对象
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      throw new Error(`打包文档失败: ${errorMessage}`);
    }
  }
}